﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Niti.OrderManage.Application.Contracts;
using Niti.OrderManage.DTO;
using Niti.OrderManage.Enum;
using Niti.OrderManage.Eto;
using Niti.OrderManage.OrderManage;
using Niti.OrderManage.OrderManage.Enum;
using Niti.OrderManage.OrderManage.Repositories;
using Niti.OrderManage.OrderManage.ValueObject;
using Niti.OrderManage.ToolKits.Base;
using Niti.OrderManage.ToolKits.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Domain.Entities.Events;
using Volo.Abp.EventBus;
using Volo.Abp.EventBus.Local;
using Volo.Abp.Uow;
using static Niti.OrderManage.NitiOrderManageConsts;

namespace Niti.OrderManage.Order.Impl
{
    [ApiController]
    [Route("[controller]/[action]")]
    [ApiExplorerSettings(GroupName = Grouping.GroupName_v2)]
    public class OrderManageService : NitiOrderManageApplicationServiceBase
          , ILocalEventHandler<EntityDeletingEventData<Commodity>>
          , ILocalEventHandler<EntityDeletingEventData<Supplier>>
          , ILocalEventHandler<CheckOrderExistsEto>

    {

        private readonly IOrderRepository _orderRepository;
        private readonly IOrderLineItemRepository _orderLineItemRepository;


        private readonly ILocalEventBus _localEventBus;
        private readonly IUnitOfWorkManager _unitOfWorkManager;
        private readonly ILogger _logger;

        public OrderManageService(IOrderRepository orderRepository,
            IOrderLineItemRepository orderLineItemRepository,

               ILocalEventBus localEventBus,
            IUnitOfWorkManager unitOfWorkManager,
            ILogger<OrderManageService> logger)
        {
            _orderRepository = orderRepository;
            _orderLineItemRepository = orderLineItemRepository;

            _localEventBus = localEventBus;
            _unitOfWorkManager = unitOfWorkManager;
            _logger = logger;
        }


        #region 订单操作
        /// <summary>
        /// 新增订单
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ServiceResult<string>> InsertOrderAsync(AddOrderDto dto)
        {
            var result = new ServiceResult<string>();
            try
            {
                //查询是否有该订单
                var entityExist = await _orderRepository.FindAsync(x => x.Code == dto.Code);
                if (entityExist != null)
                {
                    result.IsFailed(ResponseText.INSERT_FAILED + ",已存在该订单");
                    return result;
                }

                var order_Supplier = new Order_Supplier(dto.Supplier_Code, dto.Supplier_SName);

                //发布供应商校验事件
                await PublishSupplierAsync(dto.Supplier_Code);



                //订单
                var orderentity = new OrderManage.Order(dto.Code, dto.Title, order_Supplier);
                //订单明细   
                foreach (var item in dto.OrderLineItem)
                {
                    //订单明细商品
                    var orderLineItem_Commodity = new OrderLineItem_Commodity(item.Commodity_Code, item.Commodity_CName, item.Commodity_CPrice);

                    //发布供应商校验事件
                    await PublishCommodityAsync(orderLineItem_Commodity);
                    //校验明细商品数量
                    if (item.Count <= 0)
                    {
                        result.IsFailed(ResponseText.INSERT_FAILED + ",采购数量必须大于0");
                        return result;
                    }
                    orderentity.AddOrChangeItem(dto.Code, orderLineItem_Commodity, item.Count);
                }
                await _orderLineItemRepository.InsertManyAsync(orderentity.OrderLineItem);
                var post = await _orderRepository.InsertAsync(orderentity);
                await _unitOfWorkManager.Current.SaveChangesAsync();
                if (post == null)
                {
                    result.IsFailed(ResponseText.INSERT_FAILED);
                    return result;
                }

                result.IsSuccess(ResponseText.INSERT_SUCCESS);


            }
            catch (Exception ex)
            {
                _logger.LogError(ex.ToString());
                result.IsFailed(ResponseText.INSERT_FAILED);
            }

            return result;
        }

        /// <summary>
        /// 修改订单
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<ServiceResult<string>> UpdateOrderAsync(AddOrderDto dto)
        {
            var result = new ServiceResult<string>();
            try
            {
                //查询是否有该订单
                var entityExist = await _orderRepository.FindAsync(x => x.Code == dto.Code);
                if (entityExist == null)
                {
                    result.IsFailed(ResponseText.UPDATE_FAILED + ",没有该订单");
                    return result;
                }
                //状态校验
                if (entityExist.IsDraft != OrderStatusCode.Draft)
                {
                    result.IsFailed(ResponseText.UPDATE_FAILED + ",该订单已审核");
                    return result;
                }
                //订单供应商校验，是否有该供应商或者和该供应商合作时间结束
                //发布供应商校验事件
                await PublishSupplierAsync(dto.Supplier_Code);
                //订单修改时间
                entityExist.UpdateTime = DateTime.Now;
                entityExist.Supplier_Code = dto.Supplier_Code;
                entityExist.Supplier_SName = dto.Supplier_SName;
                entityExist.Title = dto.Title;

                //旧版订单明细   
                var orderLineItementity = _orderLineItemRepository.Where(x => x.OrderCode == dto.Code).ToList();
                //订单明细调整
                foreach (var item in dto.OrderLineItem)
                {
                    //订单明细商品
                    var orderLineItem_Commodity = new OrderLineItem_Commodity(item.Commodity_Code, item.Commodity_CName, item.Commodity_CPrice);
                    //发布供应商校验事件
                    await PublishCommodityAsync(orderLineItem_Commodity);
                    //校验明细商品数量
                    if (item.Count <= 0)
                    {
                        result.IsFailed(ResponseText.UPDATE_FAILED + ",采购数量必须大于0");
                        return result;
                    }
                    entityExist.AddOrChangeItem(dto.Code, orderLineItem_Commodity, item.Count,true);
                }

                await _orderLineItemRepository.DeleteManyAsync(orderLineItementity);//删除旧版明细
                await _orderLineItemRepository.InsertManyAsync(entityExist.OrderLineItem);//新增新版明细
                var post = await _orderRepository.UpdateAsync(entityExist);
                await _unitOfWorkManager.Current.SaveChangesAsync();
                if (post == null)
                {
                    result.IsFailed(ResponseText.UPDATE_FAILED);
                    return result;
                }

                result.IsSuccess(ResponseText.UPDATE_SUCCESS);
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogCritical(ex.ToString());
                result.IsFailed(ResponseText.UPDATE_FAILED);
            }

            return result;
        }

        /// <summary>
        ///删除订单
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>

        [HttpDelete]
        public async Task<ServiceResult<string>> DeleteOrderAsync(string code)
        {
            var result = new ServiceResult<string>();
            try
            {
                //查询是否有该订单
                var entityExist = await _orderRepository.FindAsync(x => x.Code == code);
                if (entityExist == null)
                {
                    result.IsFailed(ResponseText.DELETE_FAILED + ",没有该订单");
                    return result;
                }
                //状态校验
                if (entityExist.IsDraft != OrderStatusCode.Draft)
                {
                    result.IsFailed(ResponseText.DELETE_FAILED + ",该订单已审核");
                    return result;
                }

                //订单明细   
                var orderLineItementity = _orderLineItemRepository.Where(x => x.OrderCode == code).ToList();

                await _orderLineItemRepository.DeleteManyAsync(orderLineItementity);
                await _orderRepository.DeleteAsync(entityExist);
                await _unitOfWorkManager.Current.SaveChangesAsync();

                result.IsSuccess(ResponseText.DELETE_SUCCESS);


            }
            catch (Exception ex)
            {
                _logger.LogError(ex.ToString());
                result.IsFailed(ResponseText.DELETE_FAILED);
            }

            return result;
        }

        /// <summary>
        /// 根据订单号查询订单
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ServiceResult<OrderDto>> GetOrderAsync(string code)
        {
            ServiceResult<OrderDto> result = new ServiceResult<OrderDto>();
            try
            {
                var entity = await _orderRepository.FindAsync(x => x.Code == code);
                // var temp= await _orderRepository.WithDetailsAsync(x => x.Code == code);
                if (entity == null)
                {
                    result.IsFailed(ResponseText.WHAT_NOT_EXIST.FormatWith("订单号", code));
                    return result;
                }
                result.IsSuccess("ok");
                //返回dto
                OrderDto dto = new OrderDto()
                {
                    Code = entity.Code,
                    Count = entity.Count,
                    CreationTime = entity.CreationTime,
                    Supplier_Code = entity.Supplier_Code,
                    Supplier_SName = entity.Supplier_SName,
                    Title = entity.Title,
                    TotalPrice = entity.TotalPrice,
                    UpdateTime = entity.UpdateTime
                };
                //订单明细   
                List<OrderLineItemDto> list = new List<OrderLineItemDto>();
                var orderLineItementity = _orderLineItemRepository.Where(x => x.OrderCode == code).ToList();
                foreach (var item in orderLineItementity)
                {
                    list.Add(new OrderLineItemDto
                    {
                        Commodity_CName = item.Commodity_CName,
                        Commodity_Code = item.Commodity_Code,
                        Commodity_CPrice = item.Commodity_CPrice,
                        Count = item.Count,
                        CreationTime = item.CreationTime,
                        LineNumber = item.LineNumber,
                        Subtotal = item.Subtotal,
                        UpdateTime = item.UpdateTime
                    });
                }
                dto.OrderLineItem = list;
                result.Result = dto;

            }
            catch (Exception ex)
            {
                result.IsFailed(ResponseText.WHAT_NOT_EXIST.FormatWith("订单号", code));
                _logger.LogError(ex.ToString());
            }
            return result;
        }

        /// <summary>
        /// 订单审核
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ServiceResult<string>> CheckOrderAsync(string code)
        {
            var result = new ServiceResult<string>();
            try
            {
                //查询是否有该订单
                var entityExist = await _orderRepository.FindAsync(x => x.Code == code);
                if (entityExist == null)
                {
                    result.IsFailed("不存在该订单");
                    return result;
                }
                //状态校验
                if (entityExist.IsDraft != OrderStatusCode.Draft)
                {
                    result.IsFailed("该订单已审核");
                    return result;
                }
                entityExist.IsDraft = OrderStatusCode.NoDraft;
                entityExist.CheckTime = DateTime.Now;
                var post = await _orderRepository.UpdateAsync(entityExist);
                if (post == null)
                {
                    result.IsFailed("审核失败");
                    return result;
                }
                result.IsSuccess("审核成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.ToString());
                result.IsFailed("审核失败");
            }
            return result;
        }


        /// <summary>
        /// 高级查询
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize"></param>
        /// <param name="title"></param>
        /// <param name="supplier_Code"></param>
        /// <param name="supplier_SName"></param>
        /// <param name="isDraft"></param>
        /// <param name="beginTime"></param>
        /// <param name="endtime"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ServiceResult<PagedList<OrderDto>>> GetOrderListAsync(int pageIndex = 1, int pageSize = 10, string title = "", string supplier_Code = "", string supplier_SName = "", OrderStatusCode isDraft = OrderStatusCode.All, string beginTime = "1990-10-15", string endtime = "")
        {
            var result = new ServiceResult<PagedList<OrderDto>>();
            try
            {
                //校验时间
                if ((!string.IsNullOrEmpty(beginTime) && !string.IsNullOrEmpty(endtime)) && (DateTime.Compare(Convert.ToDateTime(beginTime), Convert.ToDateTime(endtime)) > 0))
                {
                    result.IsFailed("查询失败,开始时间大于结束时间");
                    return result;
                }

                if (string.IsNullOrEmpty(endtime))
                    endtime = DateTime.Now.ToShortDateString();




                var entitylist = (from orders in await _orderRepository.GetListAsync()
                                  where (string.IsNullOrEmpty(title) || orders.Title.Contains(title))
                                         && (string.IsNullOrEmpty(supplier_Code) || orders.Supplier_Code == supplier_Code)
                                         && (string.IsNullOrEmpty(supplier_SName) || orders.Supplier_SName == supplier_SName)
                                         && ((isDraft == OrderStatusCode.All) || orders.IsDraft == isDraft)
                                         && ((string.IsNullOrEmpty(beginTime) && string.IsNullOrEmpty(endtime)) || (orders.CreationTime >= Convert.ToDateTime(beginTime) && orders.CreationTime <= Convert.ToDateTime(endtime).AddDays(1)))
                                  orderby orders.CreationTime descending
                                  select new OrderDto
                                  {
                                      Code = orders.Code,
                                      Title = orders.Title,
                                      Supplier_Code = orders.Supplier_Code,
                                      Supplier_SName = orders.Supplier_SName,
                                      Count = orders.Count,
                                      TotalPrice = orders.TotalPrice,
                                      CreationTime = orders.CreationTime,
                                      IsDraft = orders.IsDraft
                                  }).OrderByDescending(m => m.CreationTime);

                if (pageIndex < 0 || pageSize < 0)
                {
                    var list = entitylist.ToList();
                    result.IsSuccess(new PagedList<OrderDto>(list.Count, list));
                }
                else
                {
                    var list = entitylist.Skip(pageSize * (pageIndex - 1)).Take(pageSize).ToList();
                    result.IsSuccess(new PagedList<OrderDto>(list.Count, list.ToList()));
                }

            }
            catch (Exception ex)
            {
                _logger.LogError(ex.ToString());
                result.IsFailed("查询失败");
            }

            return result;
        }

        #region 废弃
        ///// <summary>
        ///// 分页查询
        ///// </summary>
        ///// <param name="input">页面和分页数</param>
        ///// <param name="conditionvalue">查询条件值</param>
        ///// <param name="condition">查询条件</param>
        ///// <returns></returns>
        //[HttpPost]
        //[Route("GetOrderListAsync")]
        //public async Task<ServiceResult<PagedList<OrderDto>>> GetOrderListAsync(OrderSelectCondition conditionvalue)
        //{
        //    var result = new ServiceResult<PagedList<OrderDto>>();
        //    try
        //    {
        //        PagingInput input = conditionvalue.input;
        //        ConditionCode condition = conditionvalue.condition;
        //        if (condition == ConditionCode.Title)
        //        {
        //            //查询标题
        //            if (string.IsNullOrEmpty(conditionvalue.Title))
        //            {
        //                result.IsFailed("选择标题，查询标题不能为空");
        //                return result;
        //            }
        //            else
        //            {
        //                var list = (from orders in await _orderRepository.GetListAsync()
        //                            where orders.Title.Contains(conditionvalue.Title)
        //                            orderby orders.CreationTime descending
        //                            select new OrderDto
        //                            {
        //                                Code = orders.Code,
        //                                Title = orders.Title,
        //                                Supplier_Code = orders.Supplier_Code,
        //                                Supplier_SName = orders.Supplier_SName,
        //                                Count = orders.Count,
        //                                TotalPrice = orders.TotalPrice,
        //                                CreationTime = orders.CreationTime,
        //                                IsDraft = orders.IsDraft
        //                            }).OrderByDescending(m => m.CreationTime).Skip(input.Limit * (input.Page - 1)).Take(input.Limit).ToList();
        //                result.IsSuccess(new PagedList<OrderDto>(list.Count, list));
        //            }
        //        }
        //        else if (condition == ConditionCode.Supplier_Code)
        //        {
        //            //查询供应商编号
        //            if (string.IsNullOrEmpty(conditionvalue.Supplier_Code))
        //            {
        //                result.IsFailed("选择供应商编号，查询供应商编号不能为空");
        //                return result;
        //            }
        //            else
        //            {
        //                var list = (from orders in await _orderRepository.GetListAsync()
        //                            where orders.Supplier_Code == conditionvalue.Supplier_Code.Trim()
        //                            orderby orders.CreationTime descending
        //                            select new OrderDto
        //                            {
        //                                Code = orders.Code,
        //                                Title = orders.Title,
        //                                Supplier_Code = orders.Supplier_Code,
        //                                Supplier_SName = orders.Supplier_SName,
        //                                Count = orders.Count,
        //                                TotalPrice = orders.TotalPrice,
        //                                CreationTime = orders.CreationTime,
        //                                IsDraft = orders.IsDraft
        //                            }).OrderByDescending(m => m.CreationTime).Skip(input.Limit * (input.Page - 1)).Take(input.Limit).ToList();
        //                result.IsSuccess(new PagedList<OrderDto>(list.Count, list));
        //            }
        //        }
        //        else if (condition == ConditionCode.Supplier_SName)
        //        {
        //            //查询供应商名称
        //            if (string.IsNullOrEmpty(conditionvalue.Supplier_SName))
        //            {
        //                result.IsFailed("选择供应商名称，查询供应商名称不能为空");
        //                return result;
        //            }
        //            else
        //            {
        //                var list = (from orders in await _orderRepository.GetListAsync()
        //                            where orders.Supplier_SName == conditionvalue.Supplier_SName.Trim()
        //                            orderby orders.CreationTime descending
        //                            select new OrderDto
        //                            {
        //                                Code = orders.Code,
        //                                Title = orders.Title,
        //                                Supplier_Code = orders.Supplier_Code,
        //                                Supplier_SName = orders.Supplier_SName,
        //                                Count = orders.Count,
        //                                TotalPrice = orders.TotalPrice,
        //                                CreationTime = orders.CreationTime,
        //                                IsDraft = orders.IsDraft
        //                            }).OrderByDescending(m => m.CreationTime).Skip(input.Limit * (input.Page - 1)).Take(input.Limit).ToList();
        //                result.IsSuccess(new PagedList<OrderDto>(list.Count, list));
        //            }
        //        }
        //        else if (condition == ConditionCode.IsDraft)
        //        {
        //            //查询审核条件的
        //            if (!System.Enum.IsDefined(typeof(OrderStatusCode), conditionvalue.IsDraft))
        //            {
        //                result.IsFailed("选择审核条件，查询审核条件不能不在枚举类型内");
        //                return result;
        //            }
        //            else
        //            {
        //                var list = (from orders in await _orderRepository.GetListAsync()
        //                            where orders.IsDraft == conditionvalue.IsDraft
        //                            orderby orders.CreationTime descending
        //                            select new OrderDto
        //                            {
        //                                Code = orders.Code,
        //                                Title = orders.Title,
        //                                Supplier_Code = orders.Supplier_Code,
        //                                Supplier_SName = orders.Supplier_SName,
        //                                Count = orders.Count,
        //                                TotalPrice = orders.TotalPrice,
        //                                CreationTime = orders.CreationTime,
        //                                IsDraft = orders.IsDraft
        //                            }).OrderByDescending(m => m.CreationTime).Skip(input.Limit * (input.Page - 1)).Take(input.Limit).ToList();
        //                result.IsSuccess(new PagedList<OrderDto>(list.Count, list));
        //            }
        //        }
        //        else if (condition == ConditionCode.Time)
        //        {
        //            //查询时间范围的
        //            if (string.IsNullOrEmpty(conditionvalue.BeginTime.ToString()) || string.IsNullOrEmpty(conditionvalue.Endtime.ToString()))
        //            {
        //                result.IsFailed("选择时间范围，开始时间和结束时间不能为空");
        //                return result;
        //            }
        //            else
        //            {
        //                if (DateTime.Compare(conditionvalue.BeginTime, conditionvalue.Endtime) > 0)
        //                {
        //                    result.IsFailed("选择时间范围，开始时间小于等于结束时间");
        //                    return result;
        //                }
        //                var list = (from orders in await _orderRepository.GetListAsync()
        //                            where orders.CreationTime >= conditionvalue.BeginTime && orders.CreationTime <= conditionvalue.Endtime
        //                            orderby orders.CreationTime descending
        //                            select new OrderDto
        //                            {
        //                                Code = orders.Code,
        //                                Title = orders.Title,
        //                                Supplier_Code = orders.Supplier_Code,
        //                                Supplier_SName = orders.Supplier_SName,
        //                                Count = orders.Count,
        //                                TotalPrice = orders.TotalPrice,
        //                                CreationTime = orders.CreationTime,
        //                                IsDraft = orders.IsDraft
        //                            }).OrderByDescending(m => m.CreationTime).Skip(input.Limit * (input.Page - 1)).Take(input.Limit).ToList();
        //                result.IsSuccess(new PagedList<OrderDto>(list.Count, list));
        //            }
        //        }
        //        else
        //        {
        //            result.IsFailed("选择查询条件不在枚举类型内");
        //            return result;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        _logger.LogError(ex.ToString());
        //        result.IsFailed("查询失败");
        //    }

        //    return result;
        //} 
        #endregion

        #endregion

        #region 明细操作
        /// <summary>
        /// 追加明细
        /// </summary>
        /// <param name="code">订单号</param>
        /// <param name="dto">明细</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ServiceResult<string>> AddOrderLineItemAsync(string code, OrderItemDto dto)
        {
            var result = new ServiceResult<string>();
            try
            {
                //查询是否有该订单
                var entityExist = await _orderRepository.FindAsync(x => x.Code == code);
                if (entityExist == null)
                {
                    result.IsFailed(ResponseText.INSERT_FAILED + ",不存在该订单");
                    return result;
                }
                //状态校验
                if (entityExist.IsDraft != OrderStatusCode.Draft)
                {
                    result.IsFailed(ResponseText.INSERT_FAILED + ",该订单已审核");
                    return result;
                }

                //发布供应商校验事件
                var orderLineItem_Commodity = new OrderLineItem_Commodity(dto.Commodity_Code, dto.Commodity_CName, dto.Commodity_CPrice);
                await PublishCommodityAsync(orderLineItem_Commodity);

                //如果有该商品则修改商品数量，没有该商品则追加一条

                //查询原明细
                var orderLineItemList = _orderLineItemRepository.Where(x => x.OrderCode == code).ToList();
                //校验明细商品数量
                if (dto.Count <= 0)
                {
                    result.IsFailed(ResponseText.INSERT_FAILED + ",采购数量必须大于0");
                    return result;
                }
                bool isInsert = entityExist.AddItem(code, orderLineItem_Commodity, dto.Count, orderLineItemList);
                if (isInsert)
                {
                    await _orderLineItemRepository.InsertAsync(entityExist.OrderLineItem.Last<OrderLineItem>());
                }
                else
                {
                    await _orderLineItemRepository.UpdateManyAsync(entityExist.OrderLineItem);
                }

                var post = await _orderRepository.UpdateAsync(entityExist);
                await _unitOfWorkManager.Current.SaveChangesAsync();
                if (post == null)
                {
                    result.IsFailed(ResponseText.INSERT_FAILED);
                    return result;
                }

                result.IsSuccess(ResponseText.INSERT_SUCCESS);

            }
            catch (Exception ex)
            {
                _logger.LogError(ex.ToString());
                result.IsFailed(ResponseText.INSERT_FAILED);
            }
            return result;
        }

        /// <summary>
        /// 修改明细
        /// </summary>
        /// <param name="code">订单号</param>
        /// <param name="dto">明细</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ServiceResult<string>> UpdateOrderLineItemAsync(string code, OrderItemDto dto)
        {
            var result = new ServiceResult<string>();
            try
            {
                //查询是否有该订单
                var entityExist = await _orderRepository.FindAsync(x => x.Code == code);
                if (entityExist == null)
                {
                    result.IsFailed(ResponseText.UPDATE_FAILED + ",不存在该订单");
                    return result;
                }
                //状态校验
                if (entityExist.IsDraft != OrderStatusCode.Draft)
                {
                    result.IsFailed(ResponseText.UPDATE_FAILED + ",该订单已审核");
                    return result;
                }
                //发布供应商校验事件
                var orderLineItem_Commodity = new OrderLineItem_Commodity(dto.Commodity_Code, dto.Commodity_CName, dto.Commodity_CPrice);
                await PublishCommodityAsync(orderLineItem_Commodity);

                //查询原明细
                var orderLineItemList = _orderLineItemRepository.Where(x => x.OrderCode == code).ToList();
                //校验明细商品数量
                if (dto.Count <= 0)
                {
                    result.IsFailed(ResponseText.UPDATE_FAILED + ",采购数量必须大于0");
                    return result;
                }
                entityExist.ChangeItem(code, orderLineItem_Commodity, dto.Count, orderLineItemList);
                await _orderLineItemRepository.UpdateManyAsync(entityExist.OrderLineItem);
                var post = await _orderRepository.UpdateAsync(entityExist);
                await _unitOfWorkManager.Current.SaveChangesAsync();
                if (post == null)
                {
                    result.IsFailed(ResponseText.UPDATE_FAILED);
                    return result;
                }

                result.IsSuccess(ResponseText.UPDATE_SUCCESS);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.ToString());
                result.IsFailed(ResponseText.UPDATE_FAILED);
            }
            return result;
        }

        /// <summary>
        /// 删除明细
        /// </summary>
        /// <param name="code">订单号</param>
        /// <param name="lineNumber">行号</param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<ServiceResult<string>> DeleteOrderLineItemAsync(string code, int lineNumber)
        {
            var result = new ServiceResult<string>();
            try
            {
                //查询是否有该订单
                var entityExist = await _orderRepository.FindAsync(x => x.Code == code);
                if (entityExist == null)
                {
                    result.IsFailed(ResponseText.DELETE_FAILED + ",不存在该订单");
                    return result;
                }
                //状态校验
                if (entityExist.IsDraft != OrderStatusCode.Draft)
                {
                    result.IsFailed(ResponseText.DELETE_FAILED + ",该订单已审核");
                    return result;
                }

                //查询原明细
                var orderLineItemList = _orderLineItemRepository.Where(x => x.OrderCode == code).ToList();
                var orderLineItem = orderLineItemList.FirstOrDefault(x => x.LineNumber == lineNumber);
                if (orderLineItem == null)
                {
                    result.IsFailed(ResponseText.DELETE_FAILED + ",不存在该行号订单明细");
                }
                else
                {
                    orderLineItemList.Remove(orderLineItem);
                    entityExist.DeleteItem(code, orderLineItemList);
                    await _orderLineItemRepository.DeleteAsync(orderLineItem);
                    await _orderRepository.UpdateAsync(entityExist);
                    await _unitOfWorkManager.Current.SaveChangesAsync();
                    result.IsSuccess(ResponseText.DELETE_SUCCESS);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.ToString());
                result.IsFailed(ResponseText.DELETE_FAILED);
            }
            return result;
        }


        #endregion

        #region 订阅事件

        /// <summary>
        /// 订阅商品删除事件
        /// </summary>
        /// <param name="eventData"></param>
        /// <returns></returns>
        [NonAction]
        public async Task HandleEventAsync(EntityDeletingEventData<Commodity> eventData)
        {
            try
            {
                //如果存在订单包含该商品，不能删除
                var order = await _orderRepository.GetListAsync(x => x.IsDraft == OrderStatusCode.NoDraft);
                if (order != null)
                {
                    foreach (var item in order)
                    {
                        var commoditys = await _orderLineItemRepository.GetListAsync(x => x.OrderCode == item.Code);
                        if (commoditys != null)
                        {
                            foreach (var commodity in commoditys)
                            {
                                if (commodity.Commodity_Code == eventData.Entity.Code)
                                {
                                    throw new NotImplementedException("入库订单：" + item.Code + ",存在该商品" + eventData.Entity.Code);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.ToString());
                throw new NotImplementedException(ex.ToString());
            }
        }

        /// <summary>
        /// 订阅查询采购订单事件
        /// </summary>
        /// <param name="eventData"></param>
        /// <returns></returns>
        [NonAction]
        public async Task HandleEventAsync(CheckOrderExistsEto eventData)
        {
            try
            {
                //如果存在订单包含该商品，不能更新和删除
                var order = await _orderRepository.FindAsync(x => x.Code == eventData.Code && x.IsDraft == OrderStatusCode.NoDraft);
                order.OrderLineItem = await _orderLineItemRepository.GetListAsync(x => x.OrderCode == eventData.Code);
                if (order == null)
                    throw new NotImplementedException("不存在该采购订单或者该采购订单未审核");

                eventData.Order = order;

            }
            catch (Exception ex)
            {
                _logger.LogError(ex.ToString());
                throw new NotImplementedException(ex.ToString());
            }
        }

        /// <summary>
        /// 订阅供应商删除事件
        /// </summary>
        /// <param name="eventData"></param>
        /// <returns></returns>
        [NonAction]
        public async Task HandleEventAsync(EntityDeletingEventData<Supplier> eventData)
        {
            try
            {
                //如果存在订单包含该供应商，不能删除
                var order = await _orderRepository.FindAsync(x => x.IsDraft == OrderStatusCode.NoDraft && x.Supplier_Code == eventData.Entity.Code);
                if (order != null)
                {
                    throw new NotImplementedException("采购订单：" + order.Code + ",存在该供应商" + eventData.Entity.Code);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.ToString());
                throw new NotImplementedException(ex.ToString());
            }
        }

        #endregion

        #region 发布事件
        /// <summary>
        /// 发布校验商品事件
        /// </summary>
        private async Task PublishCommodityAsync(OrderLineItem_Commodity commodity)
        {
            OrderCommodityEto eto = new OrderCommodityEto(commodity);
            await _localEventBus.PublishAsync(eto);
        }
        /// <summary>
        /// 发布校验供应商事件
        /// </summary>
        /// <param name="code">供应商编号</param>
        private async Task PublishSupplierAsync(string code)
        {
            await _localEventBus.PublishAsync(
                 new OrderSupplicerEto
                 {
                     Code = code
                 }
             );
        }


        #endregion



        #region 校验供应商和商品(废弃)
        ///// <summary>
        ///// 校验供应商
        ///// </summary>
        ///// <param name="supplier"></param>
        ///// <returns></returns>
        //private async Task<bool> IsSupplierValid(Order_Supplier supplier)
        //{
        //    bool isValid = false;
        //    var entity = await _supplierRepository.FindAsync(x => x.Code == supplier.Code && x.IsDeleted == false);
        //    if (entity == null)
        //    {
        //        //result.IsFailed(ResponseText.INSERT_FAILED + ",不存在该供应商");
        //        //return result;
        //        isValid = true;
        //    }
        //    else
        //    {
        //        if (entity.EndTime != null && (DateTime.Compare((DateTime)entity.EndTime, DateTime.Now) < 0))
        //        {
        //            //result.IsFailed(ResponseText.INSERT_FAILED + ",该供应商已经过期");
        //            //return result;
        //            isValid = true;
        //        }
        //    }
        //    return isValid;
        //}
        ///// <summary>
        ///// 校验商品
        ///// </summary>
        ///// <param name="commodity"></param>
        ///// <returns></returns>
        //private async Task<bool> IsCommodityValid(OrderLineItem_Commodity commodity)
        //{
        //    bool isValid = false;
        //    var entity = await _commodityRepository.FindAsync(x => x.Code == commodity.Code && x.IsDeleted == false);
        //    if (entity == null)
        //    {
        //        isValid = true;
        //    }
        //    return isValid;
        //}

        #endregion





    }
}
